package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.WalletForm;
import com.springboot.cloud.demos.entity.po.Wallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

@Service
public class WalletService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "queryFallback")
    public Result<Wallet> query(String userId) {
        return restTemplate.getForEntity("http://producer/wallet/query?userId={1}", Result.class, userId).getBody();
    }

    public Result queryFallback(String userId) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "queryFallback")
    public<Wallet> Result get(String id) {
        return restTemplate.getForEntity("http://producer/wallet/{1}", Result.class, id).getBody();
    }

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody WalletForm form) {
        return restTemplate.postForEntity("http://producer/wallet", form, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody WalletForm form) {
        restTemplate.put("http://producer/wallet/{1}", form, form.getId());
        return Result.success();
    }

    public Result saveFallback(@RequestBody WalletForm form) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result updateFallback(WalletForm walletForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "deleteFallback")
    public Result delete(String id) {
        restTemplate.delete("http://producer/wallet/{1}", id);
        return Result.success();
    }

    public Result deleteFallback(String id) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

}
